<template>
  <div class="document-manage-container">
    <!-- 顶部搜索筛选栏 -->
    <div class="search-filter-bar">
      <div class="search-input">
        <van-icon name="search" size="16" />
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="搜索文档标题"
          @input="handleSearch"
        />
        <van-icon v-if="searchKeyword" name="clear" size="16" @click="clearSearch" />
      </div>
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="selectedType"
          :options="documentTypeOptions"
          placeholder="文档类型"
        />
        <van-dropdown-item
          v-model="selectedSort"
          :options="sortOptions"
          placeholder="排序方式"
        />
      </van-dropdown-menu>
    </div>

    <!-- 切换标签 -->
    <div class="tab-bar">
      <div
        v-for="tab in tabs"
        :key="tab.value"
        :class="['tab-item', { active: activeTab === tab.value }]"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="document-list">
      <div
        v-for="document in displayDocuments"
        :key="document.id"
        class="document-item"
        @click="goToDocumentDetail(document.id)"
      >
        <div class="document-header">
          <div class="document-icon">
            <van-icon :name="getDocumentIcon(document.doc_type)" size="24" color="#1989fa" />
          </div>
          <div class="document-info">
            <h3 class="document-title">{{ document.doc_title }}</h3>
            <div class="document-meta">
              <span class="document-type">{{ getDocumentTypeName(document.doc_type) }}</span>
              <span class="document-time">{{ formatTime(document.updateTime) }}</span>
              <span class="document-editor">{{ document.last_editor?.username || '未知用户' }}</span>
              <span v-if="document.team_id !== 0" class="document-team">{{ document.team?.name }}</span>
            </div>
          </div>
          <van-icon name="arrow" size="20" />
        </div>
        <div class="document-preview">{{ getDocumentPreview(document.doc_content || '') }}</div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && displayDocuments.length === 0" class="empty-state">
        <van-empty description="暂无文档" />
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <van-loading type="spinner" color="#1989fa" />
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="!loading && displayDocuments.length > 0" class="pagination">
      <van-pagination
        v-model:current-page="currentPage"
        :page-count="totalPages"
        show-prev-next
        show-page-size
        :page-sizes="[10, 20, 50]"
        v-model:page-size="pageSize"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      />
    </div>

    <!-- 悬浮新增按钮 -->
    <div class="floating-add-btn" @click="showAddDialog = true">
      <van-icon name="plus" size="24" color="#fff" />
    </div>

    <!-- 新增文档弹窗 -->
    <van-popup v-model:show="showAddDialog" position="top" round>
      <div class="add-dialog">
        <div class="dialog-header">
          <h3>选择文档类型</h3>
          <van-icon name="cross" size="20" @click="showAddDialog = false" />
        </div>
        <div class="document-type-grid">
          <div
            v-for="type in documentTypeOptions.filter(opt => opt.value > 0)"
            :key="type.value"
            class="document-type-item"
            @click="handleCreateDocument(type.value)"
          >
            <div class="type-icon">
              <van-icon :name="getDocumentIcon(type.value)" size="32" color="#1989fa" />
            </div>
            <span class="type-name">{{ type.text }}</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { documentStore } from '../stores/document/document';
import { userStore } from '../stores/user/user';
import type { Document } from '../models/document';

const router = useRouter();
const docStore = documentStore();
const userStoreAPI = userStore();

// 状态管理
const activeTab = ref(0); // 0-全部 1-个人 2-团队
const searchKeyword = ref('');
const selectedType = ref(0); // 0-全部类型
const selectedSort = ref(0); // 0-最新编辑 1-创建时间
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const showAddDialog = ref(false);

// 标签选项
const tabs = [
  { label: '全部文档', value: 0 },
  { label: '个人文档', value: 1 },
  { label: '团队文档', value: 2 }
];

// 文档类型选项
const documentTypeOptions = [
  { text: '全部类型', value: 0 },
  { text: '日报', value: 1 },
  { text: '周报', value: 2 },
  { text: '月报', value: 3 },
  { text: '自定义文档', value: 4 }
];

// 排序选项
const sortOptions = [
  { text: '最新编辑', value: 0 },
  { text: '创建时间', value: 1 }
];

// 计算属性
const displayDocuments = computed(() => {
  let documents = [...docStore.documents];

  // 根据标签筛选
  if (activeTab.value === 1) {
    documents = documents.filter(doc => doc.team_id === 0);
  } else if (activeTab.value === 2) {
    documents = documents.filter(doc => doc.team_id !== 0);
  }

  // 根据类型筛选
  if (selectedType.value > 0) {
    documents = documents.filter(doc => doc.doc_type === selectedType.value);
  }

  // 根据搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    documents = documents.filter(doc => 
      doc.doc_title.toLowerCase().includes(keyword) ||
      (doc.doc_content && doc.doc_content.toLowerCase().includes(keyword))
    );
  }

  // 排序
  documents.sort((a, b) => {
    if (selectedSort.value === 0) {
      return new Date(b.updateTime).getTime() - new Date(a.updateTime).getTime();
    } else {
      return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
    }
  });

  return documents;
});

const totalPages = computed(() => {
  return Math.ceil(docStore.totalCount / pageSize.value);
});

// 辅助函数
const getDocumentTypeName = (type: number) => {
  return docStore.getDocumentTypeName(type);
};

const getDocumentIcon = (type: number) => {
  const iconMap: Record<number, string> = {
    1: 'file-text-o',
    2: 'calendar-o',
    3: 'clock-o',
    4: 'document-o'
  };
  return iconMap[type] || 'document-o';
};

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } else if (diffDays === 1) {
    return '昨天';
  } else if (diffDays < 7) {
    return `${diffDays}天前`;
  } else {
    return `${date.getMonth() + 1}-${String(date.getDate()).padStart(2, '0')}`;
  }
};

const getDocumentPreview = (content: string) => {
  // 移除HTML标签
  const text = content.replace(/<[^>]*>/g, '');
  return text.length > 100 ? text.substring(0, 100) + '...' : text || '暂无内容';
};

// 方法
const loadDocuments = async () => {
  loading.value = true;
  try {
    await docStore.fetchDocumentList({
      page: currentPage.value,
      page_size: pageSize.value,
      doc_type: selectedType.value > 0 ? selectedType.value : undefined,
      order_by: selectedSort.value === 0 ? 'updateTime' : 'createTime',
      order_type: 'desc'
    });
  } catch (error) {
    showToast('加载文档失败');
  } finally {
    loading.value = false;
  }
};

const switchTab = (tab: number) => {
  activeTab.value = tab;
  currentPage.value = 1;
  loadDocuments();
};

const handleSearch = () => {
  currentPage.value = 1;
  // 可以添加防抖处理
  loadDocuments();
};

const clearSearch = () => {
  searchKeyword.value = '';
  currentPage.value = 1;
  loadDocuments();
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadDocuments();
};

const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadDocuments();
};

const goToDocumentDetail = (docId: number) => {
  router.push(`/document/detail/${docId}`);
};

const handleCreateDocument = async (type: number) => {
  showAddDialog.value = false;
  try {
    // 创建不同类型的文档
    const title = getTypeDefaultTitle(type);
    const res = await docStore.createDocument({
      doc_title: title,
      doc_type: type,
      doc_content: getTypeDefaultContent(type),
      team_id: activeTab.value === 2 ? undefined : 0,
      permission: 2
    });
    
    if (res.code === 200) {
      showToast('创建成功');
      // 重新加载列表
      await loadDocuments();
      // 跳转到新创建的文档
      router.push(`/document/detail/${res.data.id}`);
    } else {
      showToast('创建失败');
    }
  } catch (error) {
    showToast('创建失败');
  }
};

const getTypeDefaultTitle = (type: number): string => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  switch (type) {
    case 1: // 日报
      return `${year}.${month}.${day} 日报`;
    case 2: // 周报
      const weekStart = new Date(date);
      weekStart.setDate(date.getDate() - date.getDay());
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);
      return `${year}年第${Math.ceil((date.getTime() - new Date(year, 0, 1).getTime()) / (7 * 24 * 60 * 60 * 1000))}周周报`;
    case 3: // 月报
      return `${year}年${month}月 月报`;
    default: // 自定义
      return `新建文档 ${Date.now()}`;
  }
};

const getTypeDefaultContent = (type: number): string => {
  switch (type) {
    case 1: // 日报
      return `<h2>今日工作</h2><p>1. </p><p>2. </p><h2>遇到的问题</h2><p></p><h2>明日计划</h2><p>1. </p><p>2. </p>`;
    case 2: // 周报
      return `<h2>本周工作</h2><p>1. </p><p>2. </p><h2>工作成果</h2><p></p><h2>下周计划</h2><p>1. </p><p>2. </p>`;
    case 3: // 月报
      return `<h2>本月工作回顾</h2><p>1. </p><p>2. </p><h2>团队协作情况</h2><p></p><h2>下月工作计划</h2><p>1. </p><p>2. </p>`;
    default: // 自定义
      return `<h2>文档标题</h2><p>请在此处编辑文档内容...</p>`;
  }
};

// 初始化
onMounted(async () => {
  const user = await userStoreAPI.getCurrentUser();
  if (!user) {
    showToast('请先登录');
    router.push('/login');
    return;
  }
  await loadDocuments();
});
</script>

<style scoped>
.document-manage-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.search-filter-bar {
  background-color: #fff;
  padding: 12px 16px;
  margin-bottom: 10px;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 8px 12px;
  margin-bottom: 12px;
}

.search-input input {
  flex: 1;
  border: none;
  background: transparent;
  margin: 0 8px;
  font-size: 14px;
}

.search-input input:focus {
  outline: none;
}

.tab-bar {
  display: flex;
  background-color: #fff;
  margin-bottom: 10px;
  padding: 0 16px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 14px 0;
  font-size: 15px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #1989fa;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background-color: #1989fa;
  border-radius: 1.5px;
}

.document-list {
  padding: 0 16px;
}

.document-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.document-item:active {
  transform: scale(0.98);
}

.document-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.document-icon {
  margin-right: 12px;
  margin-top: 2px;
}

.document-info {
  flex: 1;
}

.document-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.document-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 12px;
  color: #999;
}

.document-type {
  background-color: #f0f9ff;
  color: #1989fa;
  padding: 2px 6px;
  border-radius: 3px;
}

.document-preview {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.empty-state {
  padding: 60px 0;
}

.loading-state {
  padding: 40px 0;
  text-align: center;
}

.pagination {
  padding: 16px;
  background-color: #fff;
  margin-top: 10px;
}

.floating-add-btn {
  position: fixed;
  bottom: 10vh;
  right: 2vh;
  width: 7vh;
  height: 7vh;
  border-radius: 50%;
  background-color: #1989fa;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
  z-index: 100;
  cursor: pointer;
}

.floating-add-btn:active {
  transform: scale(0.9);
}

/* 新增文档弹窗 */
.add-dialog {
  padding: 20px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.document-type-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.document-type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  cursor: pointer;
}

.document-type-item:active {
  background-color: #e8e8e8;
}

.type-icon {
  margin-bottom: 12px;
}

.type-name {
  font-size: 14px;
  color: #666;
}
</style>